/*
    i2cdetect.c - a user-space program to scan for I2C devices
    Copyright (C) 1999-2004  Frodo Looijaard <frodol@dds.nl>, and
                             Mark D. Studebaker <mdsxyz123@yahoo.com>
    Copyright (C) 2004-2012  Jean Delvare <khali@linux-fr.org>
	Copyright (C) 2025  Luohao <luohao@100trust.cn>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    MA 02110-1301 USA.
*/

#include <sys/ioctl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>
#include "i2cbusses.h"
#include "i2cdriver.h"
#include <string.h>
#include "../version.h"


#define MODE_AUTO	0
#define MODE_QUICK	1
#define MODE_READ	2
#define MODE_FUNC	3

static void help(void)
{
	fprintf(stderr,
		"Usage: i2cdetect [-a] I2CBUS [FIRST LAST]\n"
		"       i2cdetect -l\n"
		"  I2CBUS is an integer or an I2C bus name\n"
		"  If provided, FIRST and LAST limit the probing range.\n");
}

/* 准备I2C传输参数的函数 */
static void prepare_i2c_params(uint32_t bus_id, uint8_t device_addr, uint32_t offset, uint8_t offset_width, 
                               struct i2c_data_s *read_params, uint8_t *tx_data) 
{
    memset(read_params, 0, sizeof(struct i2c_data_s));
    read_params->rv_id = bus_id;

    read_params->tx_data_len = offset_width + 1;
    read_params->tx_data = tx_data;
    /* I2C address format: 7-bit address left-shifted, LSB is R/W bit
     * For read operations following a write (address+offset), use write format first */
    read_params->tx_data[0] = (device_addr << 1) & 0xFE;  /* Clear R/W bit for write */

    /* Add offset bytes in big-endian format (most significant byte first) */
    for (int i = 0; i < offset_width; i++) {
        read_params->tx_data[i + 1] = (offset >> ((offset_width - i - 1) * 8)) & 0xFF;
    }
    
    read_params->timeout_cnt = 100;
    read_params->re_cnt = 1;
    read_params->read_data = NULL;
    read_params->read_data_len = 1;
}

static int scan_i2c_bus(int i2cbus, int mode, int first, int last)
{
	int i, j;
	int res;
	int fd = -1;
	uint8_t buf[1];

	/* Open I2C device */
	fd = i2c_open();
	if (fd < 0) {
		fprintf(stderr, "Error: Could not open I2C device\n");
		return -1;
	}

	/* Initialize I2C bus */
	if (i2c_init(fd, i2cbus, 0) != 0) {
		fprintf(stderr, "Error: Could not initialize I2C bus %d\n", i2cbus);
		i2c_close(fd);
		return -1;
	}

	printf("     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f\n");

	for (i = 0; i < 128; i += 16) {
		printf("%02x: ", i);
		for(j = 0; j < 16; j++) {
			fflush(stdout);

			/* Note: mode is currently ignored as we only use read operation */
			(void)mode;

			/* Skip unwanted addresses */
			if (i+j < first || i+j > last) {
				printf("   ");
				continue;
			}

			/* Probe this address using i2cdriver interface */
			/* 使用prepare_i2c_params构建I2C传输参数 */
			uint32_t offset = 0;       /* 偏移值，对于检测通常为0 */
			uint8_t tx_data[5];        /* 传输数据缓冲区 */
			struct i2c_data_s read_params;
			bool is_found = false;
			for (uint8_t offset_width = 0; offset_width < 5; offset_width++)
			{
				prepare_i2c_params((uint32_t)i2cbus, (uint8_t)(i+j), offset, offset_width, &read_params, tx_data);
				read_params.read_data_len = 1;  /* 读取数据长度（检测读1字节）*/
				res = i2c_read(fd, &read_params, buf);
				if (res == 0)
				{
					is_found = true;
					break;
				}
			}

			if (!is_found) {
				printf("-- ");
			}
			else {
				printf("%02x ", i+j);
			}
		}
		printf("\n");
	}

	i2c_close(fd);
	return 0;
}

struct func
{
	long value;
	const char* name;
};

int main(int argc, char *argv[])
{
	char *end;
	int i2cbus, res;
	int mode = MODE_AUTO;
	int first = 0x03, last = 0x77;
	int flags = 0;
	int version = 0, list = 0;

	/* handle (optional) flags first */
	while (1+flags < argc && argv[1+flags][0] == '-') {
		switch (argv[1+flags][1]) {
		case 'V': version = 1; break;
		case 'l': list = 1; break;
		case 'D': DEBUG_MODE = true; break;
		case 'r':
			if (mode == MODE_QUICK) {
				fprintf(stderr, "Error: Different modes "
					"specified!\n");
				exit(1);
			}
			mode = MODE_READ;
			break;
		case 'q':
			if (mode == MODE_READ) {
				fprintf(stderr, "Error: Different modes "
					"specified!\n");
				exit(1);
			}
			mode = MODE_QUICK;
			break;
		case 'a':
			first = 0x00;
			last = 0x7F;
			break;
		case 'h':
			help();
			exit(0);
		default:
			fprintf(stderr, "Error: Unsupported option "
				"\"%s\"!\n", argv[1+flags]);
			help();
			exit(1);
		}
		flags++;
	}

	if (version) {
		fprintf(stderr, "i2cdetect version %s\n", VERSION);
		exit(0);
	}

	if (list) {
		print_i2c_busses();
		exit(0);
	}

	if (argc < flags + 2) {
		fprintf(stderr, "Error: No i2c-bus specified!\n");
		help();
		exit(1);
	}
	i2cbus = lookup_i2c_bus(argv[flags+1]);
	if (i2cbus < 0) {
		help();
		exit(1);
	}

	/* read address range if present */
	if (argc == flags + 4 && mode != MODE_FUNC) {
		int tmp;

		tmp = strtol(argv[flags+2], &end, 0);
		if (*end) {
			fprintf(stderr, "Error: FIRST argment not a "
				"number!\n");
			help();
			exit(1);
		}
		if (tmp < first || tmp > last) {
			fprintf(stderr, "Error: FIRST argument out of range "
				"(0x%02x-0x%02x)!\n", first, last);
			help();
			exit(1);
		}
		first = tmp;

		tmp = strtol(argv[flags+3], &end, 0);
		if (*end) {
			fprintf(stderr, "Error: LAST argment not a "
				"number!\n");
			help();
			exit(1);
		}
		if (tmp < first || tmp > last) {
			fprintf(stderr, "Error: LAST argument out of range "
				"(0x%02x-0x%02x)!\n", first, last);
			help();
			exit(1);
		}
		last = tmp;
	} else if (argc != flags + 2) {
		help();
		exit(1);
	}

	/* Print command start message to ttyS0 */
	FILE *tty = fopen("/dev/ttyS0", "w");
	if (tty != NULL) {
		fprintf(tty, "i2cdetect command started - scanning bus %d, mode %d, range 0x%02x-0x%02x\n", 
			i2cbus, mode, first, last);
		fclose(tty);
	}

	res = scan_i2c_bus(i2cbus, mode, first, last);

	exit(res?1:0);
}
